import { Auth, VerifyCodeAction } from '@hw-agconnect/cloud';
import cloud from '@hw-agconnect/cloud'
import hilog from '@ohos.hilog'
import router from '@ohos.router';

class SMS_Verification{
  countDown: number = 60
  //用一个变量来获取setinterval的ID
  intervalId: number = 0 //因为这个变量与页面显示无关所以不用@State注释
  private verifyCodeButtonEnable: boolean = false
  private verifyCodeButtonText: string = '获取验证码'
  private phoneNumber: string = ''
  private verifyCode: string = '输入验证码'
  private mainPage = `pages/MyLoginLign7ut`


  //定时器代码
  waiting() {
    this.verifyCodeButtonEnable = false
    this.verifyCodeButtonText = `${this.countDown}s` //在一点击时，就显示10S
    this.intervalId = setInterval(() => { //要知道定时器结束没有需要知道它的返回结果，这个结果可以通过setinterval的ID获取。
      this.verifyCodeButtonText = `${this.countDown}s` //将倒计时显示出来
      if (this.countDown < 0) {
        //如果减到0，清楚定时器
        clearInterval(this.intervalId) //得到返回结果后清楚定时器
        this.countDown = 10
        this.intervalId = 0
        this.verifyCodeButtonText = '获取验证码' //倒计时结束时回复
        this.verifyCodeButtonEnable = true //当点击时按键不可用
        return //不需要再往下继续执行了，所以return
      }
      this.countDown--
    }, 1000) //每隔1秒减一次
  }

  judgement() {
    if (this.phoneNumber.length === 11) {
      this.verifyCodeButtonEnable = true
    } else {
      this.verifyCodeButtonEnable = false
    }
  }

  async sending_verifyCode() {
    try { //调用方式异步调用
      await cloud.auth().requestVerifyCode({
        verifyCodeType: {
          kind: 'phone',
          phoneNumber: this.phoneNumber,
          countryCode: '86'
        },
        action: VerifyCodeAction.REGISTER_LOGIN, //验证的方式
        lang: 'zh_CN',
        sendInterval: 10
      })
      hilog.info(0, 'VerifCode', 'Success')
    } catch (e) {
      //AlertDialog.show({ title: '错误', message: '获取验证码失败' }) //弹窗内容
      hilog.info(0, 'VerifCode', JSON.stringify(e))
    }
  }


  async login_verify() {
    try {
      const result = await cloud.auth().signIn({ //定义一个变量来接收它的返回结果,返回的是result，在通过result.gitUsr获取用户信息
        credentialInfo: {
          kind: 'phone',
          countryCode: '86',
          phoneNumber: this.phoneNumber,
          verifyCode: this.verifyCode
        }
      })
      const user = result.getUser()
      AppStorage.SetOrCreate('user', user) //存储用户到 AppStorage
      hilog.info(0, 'Login', 'Success')
      router.replaceUrl({ url: 'pages/Loading' })
    } catch (e) {
      //AlertDialog.show({ title: '错误', message: '登陆失败' })
      hilog.info(0, 'Login', JSON.stringify(e))
    }
  }
}
const getSMS_verification = new SMS_Verification();
export default getSMS_verification as SMS_Verification